import BigNumber from "bignumber.js";

export type URLParamsObjType = Record<string, string | boolean | number | BigNumber>

/**
 * Url工具
 */
class URLUtil {

    /**
     * 解析 URLSearchParams 为对象
     * @param {URLSearchParams} params URL 参数
     * @param {boolean} [resolveType=true] 是否解析类型
     */
    URLSearchParamsToObj(params?: URLSearchParams, resolveType: boolean = true): URLParamsObjType {
        const obj: Record<string, string> = {}
        if (!params) return obj
        params.forEach((value, key) => {
            obj[key] = value
        })
        if (resolveType) {
            return this.resolveParamsType(obj)
        }
        return obj
    }

    /**
     * 解析参数对象中值的类型
     * @param {Record<string, string>} params 参数
     */
    resolveParamsType(params: Record<string, string>): URLParamsObjType {
        const paramsRes: URLParamsObjType = {};
        for (let paramKey in params) {
            const paramVal = params[paramKey]
            if (paramVal === 'true') {
                // 布尔 true
                paramsRes[paramKey] = true;
            } else if (paramVal === 'false') {
                // 布尔 false
                paramsRes[paramKey] = false;
            } else if (/^[+-]?\d+(?:\.\d+)?$/.test(paramVal)) {
                // 数字
                const bigNumber = new BigNumber(paramVal)
                if (bigNumber.gt(Number.MAX_SAFE_INTEGER) || bigNumber.lt(Number.MIN_SAFE_INTEGER)) {
                    // 如果不在安全范围内，则转为 bignumber
                    paramsRes[paramKey] = bigNumber
                } else {
                    if (/^[+-]?\d+$/.test(paramVal)) {
                        // 整数
                        paramsRes[paramKey] = parseInt(paramVal)
                    } else if (/^[+-]?(?:0|\d+\.\d+)$/.test(paramVal)) {
                        // 浮点数
                        paramsRes[paramKey] = parseFloat(paramVal)
                    } else {
                        // 其他
                        paramsRes[paramKey] = paramVal
                    }
                }
            } else {
                paramsRes[paramKey] = paramVal;
            }
        }
        return paramsRes
    }
}

export default new URLUtil()
